<?php

/**
 * Created by ghostsf
 * Date: 2016/4/20
 */

namespace app\admin\controller;

use app\admin\model\Config;
use app\admin\model\Personalconfig;
use think\Controller;
use think\Db;
use think\Config as redis;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use Qiniu\Processing\PersistentFop;

use JPush\Client;
/**
 * 公共
 * Class Common
 * @package app\admin\controller
 */
class CommonController extends Controller {
	public  $redis;
    /**
     * 拦截器
     *
     * @return bool
     */
    public function _initialize() {
//session过期验证
//        if (!isset($_SESSION['loginSession'])) {
//            header("http/1.1", true, 389); //389 http状态码 session过期
//            return false;
//        }
    }

    /**
     * 压缩图片
     * @param $imgsrc
     * @param $imgdst
     */
    function image_png_size_add($imgsrc,$imgdst){
        list($width,$height,$type)=getimagesize($imgsrc);
        $new_width = ($width>600?600:$width)*0.9;
        $new_height =($height>600?600:$height)*0.9;
        switch($type){
            case 1:
                break;
            case 2:
//                header('Content-Type:image/jpeg');
                $image_wp=imagecreatetruecolor($new_width, $new_height);
                $image = imagecreatefromjpeg($imgsrc);
                imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
                imagejpeg($image_wp, $imgdst,95);
                imagedestroy($image_wp);
                break;
            case 3:
//                header('Content-Type:image/png');
                $image_wp=imagecreatetruecolor($new_width, $new_height);
                $image = imagecreatefrompng($imgsrc);
                imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
                imagejpeg($image_wp, $imgdst,95);
                imagedestroy($image_wp);
                break;
        }
    }
	
	/** redis连接
     * @return bool
     */

    public function redis()
    {
        $options=redis::get('database');
        $redisHost=array_key_exists("redisHost",$options)?$options['redisHost']:"127.0.0.1";
        $redisPort=array_key_exists("redisPort",$options)?$options['redisPort']:6379;
        $redisAuth=array_key_exists("redisAuth",$options)?$options['redisAuth']:'';
        $redisHost=$redisHost==null?"127.0.0.1":$redisHost;
        $redisPort=$redisPort==null? 6379:$redisPort;
        if(extension_loaded("redis")){
            $redis= new \redis();
            if($redis->connect($redisHost,$redisPort)){
                if($redisAuth!=null){
                    $redis->auth($redisAuth);
                    if(false==$redis->set('ce',1)){
                        return false;
                    }
                }
               $this->redis=$redis;
                return true;
            }else{
                  return false;
                die;
                $tishi="redis连接失败原因IP地址连接有误";
                die($tishi);
            }

        }else{
            return false;
        }
    }

    /**
     * 全局设置
     * @param array $arr
     */
    public function setGlobalSettings($arr = []) {
        foreach ($arr as $name) {
            $config = Config::get(array("name" => $name));
            $this->assign($name, $config->value);
        }
    }

    /**
     * 个性设置
     * @param array $arr
     */
    public function setPersonalSettings($arr = []) {
        $loginSession = session('loginSession');
        $userid = $loginSession['id'];
        foreach ($arr as $name) {
            $personalConfig = Personalconfig::get(array("name" => $name, "userid" => $userid));
            if ($personalConfig) {
                $this->assign($name, $personalConfig->value);
            } else {
                $this->setGlobalSettings([$name]);
            }
        }
    }

    /**
     * 根据校区id区分数据显示
     */
    public function getDataByCampusid($arr = []) {
//为空是用来判断添加数据时要不要传参
//$str是专门用于获取数据（其他是campusid 校区管理是id） 针对校区管理 除了校区管理  其他功能不用传
        foreach ($arr as $key => $value) {
            if ($key == 'page') {
                unset($arr[$key]);
            } else if ($key == 'rows') {
                unset($arr[$key]);
            } else if ($value == '') {
                unset($arr[$key]);
            }else if($key == 'start'){
                unset($arr[$key]);
            }else if($key == 'end'){
                unset($arr[$key]);
            }else if($key == 'startTime'){
                unset($arr[$key]);
            }else if($key == 'endTime'){
                unset($arr[$key]);
            } else {
                $arr[$key] = Array('like', '%' . $value . '%');
            }
        }

        return $arr;
    }
    /**
     * 筛选搜索条件不是like是=
     */
    public function searchNotLike($searchPath=[],$postArr=[],$one='',$two='',$three='') {
        if (isset($searchPath[$one]) && $one != '') {
            unset($searchPath[$one]);
            $searchPath[$one] = $postArr[$one];
        }
        if (isset($searchPath[$two]) && $two != '') {
            unset($searchPath[$two]);
            $searchPath[$two] = $postArr[$two];
        }
        if (isset($searchPath[$three]) && $three != '') {
            unset($searchPath[$three]);
            $searchPath[$three] = $postArr[$three];
        }
        return $searchPath;
    }
    /**
     * 排课---日期处理--仅限排课使用
     * @param array $arr
     */
    public function arrangeDateSet($arr = []) {
        $beginD = strtotime($arr['schedule_starttime']);
        //计算有多少已经报名的学生用的
        $starttime = $arr['schedule_starttime'];
        //计算结束
        $overD = strtotime($arr['schedule_endtime']);
        $result = array();
//判断重复
        $param = $this->getDataByCampusid();
        $classroom = Db::table('ew_schedule')->where($param)->where('schedule_classroomid', $arr['schedule_classroomid'])->where('schedule_status', 0)->field('min(schedule_starttime) as schedule_starttime,schedule_endtime')->group('schedule_endtime')->select();
        $class = Db::table('ew_schedule')->where($param)->where('schedule_classid', $arr['schedule_classid'])->where('schedule_status', 0)->field('min(schedule_starttime) as schedule_starttime,schedule_endtime')->group('schedule_endtime')->select();
        $teacher = Db::table('ew_schedule')->where($param)->where('schedule_teacherid', $arr['schedule_teacherid'])->where('schedule_status', 0)->field('min(schedule_starttime) as schedule_starttime,schedule_endtime,schedule_classbegin,schedule_classover')->group('schedule_endtime')->select();

        if (!empty($classroom)) {
            foreach ($classroom as $room) {
                $end = strtotime($room['schedule_endtime']);
                $start = strtotime($room['schedule_starttime']);
                if ($beginD > $end || $overD < $start) {
                    continue;
                } else {
                    $result['status'] = 0;
                    $result['msg'] = '此教室在此日期范围内已被占用';
                    return $result;
                }
            }
        }
        if (!empty($class)) {
            foreach ($class as $cla) {
                $end = strtotime($cla['schedule_endtime']);
                $start = strtotime($cla['schedule_starttime']);
                if ($beginD > $end || $overD < $start) {
                    continue;
                } else {
                    $result['status'] = 0;
                    $result['msg'] = '此班级在此日期范围内已被占用';
                    return $result;
                }
            }
        }
        if (!empty($teacher)) {
            foreach ($teacher as $teach) {
                $end = strtotime($teach['schedule_endtime']);
                $start = strtotime($teach['schedule_starttime']);
                if ($beginD > $end || $overD < $start) {
                    continue;
                } else {
                    $oldbegin = explode(':', $teach['schedule_classbegin']);
                    $oldover = explode(':', $teach['schedule_classover']);
                    $newbegin = explode(':', $arr['schedule_classbegin']);
                    $newover = explode(':', $arr['schedule_classover']);
                    $oldbegin = $oldbegin[0] * 60 + $oldbegin[1];
                    $oldover = $oldover[0] * 60 + $oldover[1];
                    $newbegin = $newbegin[0] * 60 + $newbegin[1];
                    $newover = $newover[0] * 60 + $newover[1];
                    if ($newbegin > $oldover || $newover < $oldbegin) {
                        continue;
                    } else {
                        $result['status'] = 0;
                        $result['msg'] = '此老师在此日期范围上课时间段内已有排课';
                        return $result;
                    }
                }
            }
        }
//判断完毕
        $day = floor(($overD - $beginD) / 86400);
        $one = 3600 * 24;
        $week = $arr['schedule_perweek'];
        unset($arr['schedule_perweek']);
        unset($arr['schedule_starttime']);

        for ($i = 0; $i <= $day; $i++) {
            foreach ($week as $value) {
                if (date('w', $beginD + $i * $one) == $value) {
//处理关联的年级ID和课程ID
                    $classid = $arr['schedule_classid'];
                    $class = Db::table('ew_classes')->where('id', $classid)->find();
                    $courseid = $class['classes_courseid'];
                    if(empty($courseid)){
                        $result['status'] = 0;
                        $result['msg'] = '请先去完善班级 "'.$class['classes_name'].'" 的信息';
                        return $result;
                    }
                    $course = Db::table('ew_course')->where('id', $courseid)->find();
                    $gradeid = $course['course_grade_id'];
                    if(empty($gradeid)){
                        $result['status'] = 0;
                        $result['msg'] = '请先去完善课程 "'.$course['course_name'].'" 的信息';
                        return $result;
                    }
//==========处理完毕========
//处理应该招多少人和实际已有多少人
                    $student['student_classid'] = $classid;
// $student['student_gradeid'] = $gradeid;
                    $student['student_courseid'] = $courseid;
                    $student['campusid'] = $_POST['campusid'];
                    // TODO 应该添加一个时间的限制，报名日期小于开始日期的人数才对
                    $alreadtHas = Db::table('ew_student')->where($student)->where('student_status',0)->count();
                    $allowHas = Db::table('ew_classroom')->where('id', $_POST['schedule_classroomid'])->find()['classroom_containnum'];
                    if($alreadtHas > $allowHas){
                        $result['status'] = 0;
                        $result['msg'] = '此教室只能容纳'.$allowHas.'人，现已有'.$alreadtHas.'人，已满';
                        return $result;
                    }
                    $arr['schedule_prenum'] = $alreadtHas . '/' . $allowHas;
                    $arr['schedule_sctnum'] = $alreadtHas;
                    $arr['schedule_courseid'] = $courseid;
                    $arr['schedule_gradeid'] = $gradeid;
                    $arr['schedule_perweek'] = $value;
                    $arr['schedule_starttime'] = date('Y-m-d', $beginD + $i * $one);
                    $arr['schedule_status'] = 0;
                    array_push($result, $arr);
                }
            }
        }
        if (empty($result)) {
            $result['status'] = 0;
            $result['msg'] = '此日期段内无合适要求，请重新填写开始/结束日期';
            return $result;
        }
        return $result;
    }

    /**
     * 排课批量修改--查找符合条件的排课
     */
    public function getNeedData($array = []) {
// 为什么foreach出不来值
        $res = array();
        $res['schedule_classid'] = $array['schedule_classid'];
        $res['schedule_endtime'] = $array['schedule_endtime'];
        return $res;
    }

    /**
     * +----------------------------------------------------------
     * Export Excel | 2016.09.14
     * Author:ghostsf <ghostsf@163.com>
     * +----------------------------------------------------------
     * @param $expTitle     string File name
     * +----------------------------------------------------------
     * @param $expCellName  array  Column name
     * +----------------------------------------------------------
     * @param $expTableData array  Table data
     * +----------------------------------------------------------
     */
    public function exportExcel($expTitle, $expCellName, $expTableData) {
        $xlsTitle = iconv('utf-8', 'gb2312', $expTitle); //文件表名称
        $fileName = $xlsTitle . date('_YmdHis'); //文件名称
        $cellNum = count($expCellName);
        $dataNum = count($expTableData);
        vendor("phpoffice.phpexcel.Classes.PHPExcel");
        $objPHPExcel = new \PHPExcel();
        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
        $objPHPExcel->getDefaultStyle()->getFont()->setName('微软雅黑');
        $objPHPExcel->getDefaultStyle()->getFont()->setSize(12);
        $objPHPExcel->getActiveSheet()->getStyle('1')->applyFromArray(
                array(
                    'font' => array(
                        'bold' => true
                    )
                )
        );
        for ($i = 0; $i < $cellNum; $i++) {
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i] . '1', $expCellName[$i][1]);
            $objPHPExcel->getActiveSheet()->getColumnDimension($cellName[$i])->setAutoSize(true);
        }
        for ($i = 0; $i < $dataNum; $i++) {
            if($expTableData[$i]['team_member_role']==1){
                $expTableData[$i]['team_member_role']='决策层';
            }else if($expTableData[$i]['team_member_role']==2){
                $expTableData[$i]['team_member_role']='管理层';
            }else if($expTableData[$i]['team_member_role']==3){
                $expTableData[$i]['team_member_role']='成员层';
            }else{
                $expTableData[$i]['team_member_role']='成员层';
            }
            for ($j = 0; $j < $cellNum; $j++) {
                $objPHPExcel->getActiveSheet()->setCellValue($cellName[$j] . ($i + 2), $expTableData[$i][$expCellName[$j][0]]);
            }
        }
        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="' . $xlsTitle . '.xls"');
        header("Content-Disposition:attachment;filename=$fileName.xls"); //attachment新窗口打印inline本窗口打印
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        function saveExcelToLocalFile($objWriter,$fileName){
            $filePath = 'static/excel/'.$fileName.'.xls';
            $filePath = iconv("utf-8", "gb2312", $filePath);
            $objWriter->save($filePath);
            return $fileName;
        }
        $filname = saveExcelToLocalFile($objWriter,$fileName);
        return json_encode(array('msg'=>'static/excel/'.$filname.'.xls','status'=>1));

    }

    /**
     * +----------------------------------------------------------
     * Import Excel | 2016.0914
     * Author:ghostsf <ghostsf@163.com>
     * +----------------------------------------------------------
     * @param  $file   upload file $_FILES
     * +----------------------------------------------------------
     * @return array   array("error","message")
     * +----------------------------------------------------------
     */
    public function read($filename,$encode='utf-8')
   {
          vendor("phpoffice.phpexcel.Classes.PHPExcel.IOFactory");
          $objReader = \PHPExcel_IOFactory::createReader('Excel5');

          $objReader->setReadDataOnly(true);

          $objPHPExcel = $objReader->load($filename);

          $objWorksheet = $objPHPExcel->getActiveSheet();

         $highestRow = $objWorksheet->getHighestRow();
         $highestColumn = $objWorksheet->getHighestColumn();
         $highestColumnIndex = \PHPExcel_Cell::columnIndexFromString($highestColumn);
         $excelData = array();
             for ($row = 1; $row <= $highestRow; $row++) {
             for ($col = 0; $col < $highestColumnIndex; $col++) {
                 $excelData[$row][] =(string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
           }
         }
      
        return $excelData;

    }


    /**
     * @param $length
     * @return string
     * 获取uuid
     */
   public function getRandChar($length)
    {
        $chars = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
            'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
            't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
            'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
            'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
        $char_txt = '';
        for ($i = 0; $i < $length; $i++) {
            $char_txt .= $chars[array_rand($chars)];
        }
        return $char_txt;
    }

    public function httpPost($url,$post_array){
        //初始化
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, false);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //设置post方式提交
        curl_setopt($curl, CURLOPT_POST, 1);
        //设置post数据

        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_array);
        //执行命令
        $data = curl_exec($curl);
        //关闭URL请求
        curl_close($curl);
        //显示获得的数据
       return $data;
    }
    /**
     * @param $type
     * @param $rand
     * @param $exe
     * @param $filePath
     * @return mixed
     * 七牛云上传
     */
    public function qnCommon($type,$rand,$exe,$filePath)
    {
        require_once 'qiniu/autoload.php';

        if($type == 2){
            if($exe != 'jpg' && $exe != 'gif' && $exe != 'png'&&$exe != 'jpeg'&&$exe != 'x-png'&&$exe != 'pjpeg'){
                $return = array('status'=>0,'msg'=>'请上传图片');
                return $return;
            }
        }
        if($type == 3){
            if($exe != 'xls' && $exe != 'xlsx' && $exe != 'zip' && $exe != 'docx' && $exe != 'pdf'){
                $return = array('status'=>0,'msg'=>'请上传正确的文件格式');
                return $return;
            }
        }
        if($type == 4){
            if($exe != 'mp3' && $exe != 'm4a' && $exe != 'wav'){
                $return = array('status'=>0,'msg'=>'请上传正确的音频格式');
                return $return;
            }
        }
        if($type == 5){
            if($exe != 'mp4' && $exe != 'mov' && $exe != 'mkv' && $exe != 'flv' && $exe != '3gp' && $exe != 'wmv' && $exe != 'rmvb' && $exe != 'avi'){
                $return = array('status'=>0,'msg'=>'请上传正确的视频格式');
                return $return;
            }
        }
        if($type==6){
            if($exe != 'txt'){
                $return = array('status'=>0,'msg'=>'请上传正确的文本格式');
                return $return;
            }
        }
        $accessKey = '741qvMP7EBbbrND4t6_yCn95u68zwgvIwzj_tM6X';
        $secretKey = 'wQBc0mYS7Q3bioJSiA1Nsl-DKUu47Q6zmFlyEkmM';
        $bucket = 'cjtd';
        $auth = new Auth($accessKey, $secretKey);
        $returnBody = '{"key":"$(key)","mimeType":"$(mimeType)","vtime":"$(avinfo.video.duration)","atime":"$(avinfo.audio.duration)","fsize":$(fsize),"width":"$(imageInfo.width)","height":"$(imageInfo.height)","height":"$(imageInfo.height)","format":"$(imageInfo.format)"}';
        $policy = array(
            'returnBody' => $returnBody
        );
        $expires = 3600;
        $token = $auth->uploadToken($bucket, null, $expires, $policy, true);
        $key = $rand.'.'.$exe;
        $uploadMgr = new UploadManager();
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
        if ($err !== null) {
            $info = $err;
        } else {
            $info = $ret;
        }
        $info['status'] = 200;
        return $info;
    }

    public function qnCommon1($key)
    {
        require_once 'qiniu/autoload.php';

        $accessKey = '741qvMP7EBbbrND4t6_yCn95u68zwgvIwzj_tM6X';
        $secretKey = 'wQBc0mYS7Q3bioJSiA1Nsl-DKUu47Q6zmFlyEkmM';
        $bucket = 'cjtd';
//        $accessKey = '62pzsS8cWNBVDOVRxhJNejBzQCbCkAKIS5Oy0lOn';
//        $secretKey = '5HvPUZ0EzObz9z261EK5AuJntP5OT0_LV9ScDNnv';
//        $bucket = 'nanyibucketby2017year';
        $auth = new Auth($accessKey, $secretKey);

        $pipeline = 'nanyi';
        $force = false;
        $notifyUrl = 'http://cjtdcms.xuanwumobile.com/super#advert_manage';
        $config = new \Qiniu\Config();
        $pfop = new PersistentFop($auth, $config);
        $rand = date('YmdHis').rand(100000,999999);
        $fops = "avthumb/mp4/s/640x360/vb/1.4m|saveas/" . \Qiniu\base64_urlSafeEncode($bucket .  ":".$rand.'.mp4');
        list($id, $err) = $pfop->execute($bucket, $key, $fops, $pipeline, $notifyUrl, $force);
        if ($err != null) {
            $info['err'] = $err;
            $info['rand'] = $rand;
        } else {
            $info['id'] = $id;
            $info['rand'] = $rand;
        }
        return $info;
//        list($ret, $err) = $pfop->status($id);
//        echo "\n====> pfop avthumb status: \n";
//        if ($err != null) {
//            var_dump($err);
//        } else {
//            var_dump($ret);
//        }

    }
    /**
     * @param $type
     * @param $msg
     * @param $msg_encode
     * @param $data
     * @return mixed
     * 极光推送
     */
    public function sendJpush($type,$msg,$msg_encode,$msg1,$data,$code1){
        require_once 'jpush/autoload.php';
        $appkey = '777134e2bb933859e896524d';
        $masterSecret ='9aed51799173931492e02463';
        $PushClient = new Client($appkey,$masterSecret);
        $push = $PushClient->push();
        $push->setPlatform('all');
        if($type==1){
            $push->addAlias($data);
        }else{
            $push->addAllAudience();
        }

        $push->iosNotification($msg, array(
                'alert'=>$msg,
                'badge' => '1',
                'extras' => $msg_encode,
                'sound'=>'default'
            )
        );
        $push->androidNotification($msg, array(
            'badge' => '1',
            'extras' => $msg_encode
        ));
        $push->message($msg1, [
//            'title' => 'Hello',
            'content_type' => 'text',
            'extras' => [
                'key' => $code1
            ]
        ]);

        foreach ($data as $key=>$vo){
            $result['pm_id'] = $this->getRandChar(32);
            $result['pm_to_user_id'] =$vo;
            $result['pm_status'] = 2;
            $result['pm_content'] = $msg;
            $result['pm_msg_type'] = $msg_encode['code'];
            $result['pm_time'] = date('Y-m-d H:i:s');
            $res[] = $result;
        }
        Db::table('up_push_message')->insertAll($res);
        return $push->send();
    }
}
